// components/loginCheck/loginCheck.js
//获取应用实例
const app = getApp();
import { SERVERS_INFO, SERVERS_ALIAS, OTHER_INFO  } from '../../utils/api.js'

import {
  http
} from '../../utils/network.js'
import {
  PATHS_ALIAS
} from '../../utils/api.js'

Component({
  /**
   * 组件的属性列表
   */
  properties: {
    fromPage: {
      type: String,
      value: '/pages/index/index'
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    hasUserInfo: true, //是否已经授权
    impowerShow: 'hide', //授权提示弹框是否显示
    canIUse: false, //判断小程序的API，回调，参数，组件等是否在当前版本可用。
    wxUserInfo: null, //微信用户信息
    loginAgain:false,       //是否是再次授权登录
    session_key: null, //会话密钥
  },
  // 实例进入页面节点树
  attached: function () {
    
    this.setData({
      canIUse:wx.canIUse('button.open-type.getUserInfo')
    });
    
    if (this.checkLogin()) {
      return;
    } else {
      this.login();
    };


    


  },
  /**
   * 组件的方法列表
   */
  methods: { 
    // 检查登录信息是否齐全  true false
    checkLogin:function(){
      let accessToken = wx.getStorageSync('accessToken');
      let unionId = wx.getStorageSync('unionId');
      let userInfo = wx.getStorageSync('userInfo');
      let userId = wx.getStorageSync('userId');
      let mobile = wx.getStorageSync('mobile');
      if (accessToken && unionId && userInfo && userId && mobile){
        return true;
      }else{
        return false;
      }
    },
    // 再次授权--点击登录或登录回调onshow时触发
    loginAgain: function () {
      this.setData({
        loginAgain:true
      })
      if (this.data.hasUserInfo && this.data.canIUse) {
        this.login();
      } else {
        this.setData({
          impowerShow: 'show'
        });
      }
    },
    // 登录授权
    login: function () {
      
      let _this = this;
      // 登录
      wx.login({
        success: res => {
          //console.log(res);
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          this.getUserMsg(res.code);
        }
      });
      // 获取用户授权信息
      wx.getSetting({
        success: res => {
          //console.log(res);
          if (res.authSetting['scope.userInfo']) {
            // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
            wx.getUserInfo({
              success: res => {
                //console.log(res);
                // 可以将 res 发送给后台解码出 unionId
                app.globalData.userInfo = res.userInfo
                _this.setData({
                  wxUserInfo: res,
                  hasUserInfo: true
                });
                if (_this.data.loginAgain){     //授权了，但是还没登录，需要用户再次触发
                  _this.getUnionId();
                }
              }
            })
          } else if (_this.data.canIUse) {
            // 没有授权，弹框提示授权
            _this.setData({
              hasUserInfo: false
            });
          } else {
            // 在没有 open-type=getUserInfo 版本的兼容处理
            wx.getUserInfo({
              success: res => {
                app.globalData.userInfo = res.userInfo;
                _this.setData({
                  wxUserInfo: res.userInfo,
                  hasUserInfo: true
                });
                _this.getUnionId();
              }
            })
          }
        }
      })
    },
    // code换取用户信息
    getUserMsg: function (code) {
      let _this = this;
      let params = {
        code: code,
        type: 'city'
      };
      http({
        path: PATHS_ALIAS.GET_OPEN_INFO,
        params: { request: JSON.stringify(params) },
        header: {
          "content-type": "application/x-www-form-urlencoded",
          'appId': "com.smk.test.test"
        },
        success: function (res) {
          // //console.log(res);
          app.globalData.openId = res.response.openid;
          app.globalData.session_key = res.response.session_key;
          _this.setData({
            session_key: res.response.session_key
          });
        },
        complete: function () {

        }
      })
    },
    // 获取unionID
    getUnionId: function () {
      let _this = this;

      wx.showLoading({
        title: '登录中...',
        mask:true
      });
      // 请求参数齐全
      if (this.data.wxUserInfo && app.globalData.openId && this.data.session_key) {

      } else {
        setTimeout(function () {
          _this.getUnionId();
        }, 50);
        return;
      }

      // 用户获取union
      let params = {
        encryptedData: this.data.wxUserInfo.encryptedData,
        iv: this.data.wxUserInfo.iv,
        openId: app.globalData.openId,
        rawData: this.data.wxUserInfo.rawData,
        sessionKey: this.data.session_key,
        signature: this.data.wxUserInfo.signature,
        type: 'city'
      };
      http({
        path: PATHS_ALIAS.GET_UNION_ID,
        params: { request: JSON.stringify(params) },
        header: {
          "content-type": "application/x-www-form-urlencoded",
          'appId': "com.smk.test.test"
        },
        success: function (res) {
          // //console.log(res);
          if (res.code == '0') {
            app.globalData.unionId = res.response.unionId;
            wx.setStorageSync('openId', app.globalData.openId)
            wx.setStorageSync('unionId', res.response.unionId);
            wx.setStorageSync('userInfo', res.response);
            // 判断第三方登录关系
            _this.loginThird();
          } else {

          }
        },
        fail: function (err) {
          wx.showToast({
            title: '登录失败',
            icon: 'none'
          });
          wx.hideLoading();
        },
        complete: function () {

        }
      })
    },
    // 第三方用户登录
    loginThird: function () {
      let _this = this;
      let params = {
        logType: '07',
        thirdId: wx.getStorageSync('unionId'),
        resId: 'weixin',
        userSystem: '0052'
        // userSystem: '300016'
      };

      http({
        path: PATHS_ALIAS.THIRD_USER_LOGIN,
        params: params,
        header: {
          sendChl: 'hzsmk.h5',// 应用渠道(必填) 
          sendClient: 'hellohzsmk', //应用验证码(必填) string 
          clientCode: OTHER_INFO.clientCode
        },
        success: function (res) {
          // //console.log(res);
          wx.setStorageSync('accessToken', res.response.accessToken);
          wx.setStorageSync('userId', res.response.userId);
          wx.setStorageSync('mobile', res.response.mobile);
          wx.hideLoading();
          _this.triggerEvent('loginSuccess', { status: '0' });
          
          let fromPage = decodeURIComponent(_this.properties.fromPage);
          wx.navigateTo({
            url: fromPage,
          })
        },
        fail: function (err) {
          wx.hideLoading();
          wx.setStorageSync('accessToken', '');
          // wx.showToast({
          //   title: '登录失败',
          //   icon: 'none'
          // });
          // //console.log(err);
          if (err.code == 'PY0005') {    //跳转输入手机号登录
            let fromPage = encodeURIComponent(_this.properties.fromPage);
            wx.navigateTo({
              url: '/pages/phoneLogin/phoneLogin?fromPage=' + fromPage,
            })
          }
        },
        complete: function () {

        }
      })
    },
    // 获取用户信息-处理数据
    bindgetuserinfo: function (e) {
      //console.log(e)
      if (e.detail.userInfo) {
        app.globalData.userInfo = e.detail.userInfo;
        this.setData({
          wxUserInfo: e.detail,
          hasUserInfo: true
        });
        this.getUnionId();
      } else {
        this.setData({
          impowerShow: 'hide'
        })
      }
    },
    // 授权弹框-取消
    cancelGetInfo: function () {
      this.setData({
        impowerShow: 'hide'
      })
    }
  }
})
